import {HYEventStore} from "hy-event-store"
import {call} from "../yunFun/control-chat"
import {stringToArrayBuffer,arrayBufferToString} from "../untils/arrbufferHandle"

const userStore = new HYEventStore({
  state:{
    url:'wss://' + 'ckyhahaha.info' + ':3001',
    userInfo:{
      "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/E0MRCP1pKgmYaLpQcQj3ompVf5CWUGrZKR8Ce0ZickxVHO3Pvd1GYbPoWtDtg9SHfUNtCF0nWo35bXon3UP9Sqw/132",
      "nickName":"A (^o^)"
    },
    msg:[],
    socketStatus: 'closed',  // 标识是否开启socket,
    setPosition:0,
  },
  actions:{
    _getUserProfile(ctx,{userInfo}){
      ctx.userInfo = userInfo
    },
    _getMsg(ctx){
      call({type:"get"}).then(res=>{
        ctx.msg = res[0].msg
        this.dispatch("pageScrollToBottom")
      })
    },
    _addMsg(ctx,{msgItem}){
      let msg = ctx.msg 
      ctx.msg = []
      msg.push(msgItem)
      ctx.msg = msg
      call({type:"add",data:{msg}})
      this.dispatch("pageScrollToBottom")
    },
    _delMsg(ctx){
      ctx.msg = [{
        time:0,
        text:"消息记录为空",
        nickName:ctx.userInfo.nickName,
        imgUrl:ctx.userInfo.avatarUrl
      }]
      call({type:"add",data:{msg:ctx.msg}})
    },
      // 计算信息数量，使页面滚动到容器底部
    pageScrollToBottom: function (ctx) {
      ctx.setPosition = 0
      let length = parseInt(ctx.msg.length/10)
      let height = 500*(length+1)
      ctx.setPosition = height
    }, 
    _wsSend(ctx){
       // 使用websocket
      if (ctx.socketStatus === 'closed') {
        this.dispatch("openSocket")
      }
    },
    // 打开socket信道
    openSocket(ctx) {
    // 创建一个 WebSocket 连接
      wx.connectSocket({url:ctx.url})
      // 打开时的动作
      wx.onSocketOpen((res) => {
        console.log("connect success")
        ctx.socketStatus = 'connected'; // 标记打开
        wx.hideLoading()
      })
      // 监听 WebSocket 接受到服务器的消息事件
      wx.onSocketMessage(msg => {
        let strMsg = arrayBufferToString(msg)
        //把JSONStr转为JSON
        if (typeof strMsg !== 'object') {
          strMsg = strMsg.replace(/\ufeff/g, "");
          var jj = JSON.parse(strMsg);
          strMsg = jj;
        }
        this.dispatch("_addMsg",{msgItem:strMsg})
      })
  
      // 断开时的动作
      wx.onSocketClose((res) => {
        console.log('WebSocket 已断开' , res)
        this.dispatch("closeSocket")
      })
  
      // 报错时的动作
      wx.onSocketError(error => {
        console.error('socket error:', error)
      })
    },
    // 关闭信道
    closeSocket(ctx) {
      // 必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。
      if (ctx.socketStatus === 'connected') {
        // 关闭 WebSocket 连接
        wx.closeSocket({
          success: (res) => {
            console.log("关闭 WebSocket 连接" , res);
            ctx.socketStatus = 'closed'
          }
        })
      }
    },
    //发送消息函数
    sendSocketMessage(ctx,{msg}) {
      let arrBuffer = stringToArrayBuffer(msg)
      if (ctx.socketStatus === 'connected') {
        wx.sendSocketMessage({
          data: arrBuffer,
        })
      } else {
        console.log("connected error")
      }
    },
  }
})

export {userStore}